package com.googlecode.c4e.ui.actions;

import java.net.URL;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionDelegate;
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;

import com.googlecode.c4e.api.model.Server;
import com.googlecode.c4e.ui.ContinuumPlugin;

public class OpenInBrowserAction extends ActionDelegate {

	private Server server;

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection != null && selection instanceof IStructuredSelection) {
			IStructuredSelection isel = (IStructuredSelection) selection;
			if (isel.getFirstElement() instanceof Server) {
				this.server = (Server) isel.getFirstElement();
			}
		}
	}

	@Override
	public void run(IAction action) {
		if (server != null) {
			try {
				final String url = server.getUrl();
				PlatformUI.getWorkbench().getDisplay().asyncExec(
						new Runnable() {
							public void run() {
								try {
									IWorkbenchBrowserSupport browserSupport = PlatformUI
											.getWorkbench().getBrowserSupport();
									IWebBrowser browser = browserSupport
											.createBrowser(
													IWorkbenchBrowserSupport.NAVIGATION_BAR
															| IWorkbenchBrowserSupport.LOCATION_BAR,
													url, url, url);
									browser.openURL(new URL(url));
								} catch (Exception ex) {
									throw new RuntimeException(ex);
								}
							}
						});
			} catch (Exception e) {
				ContinuumPlugin.getDefault().log("openInBrowser", e);
				throw new RuntimeException(e.getMessage(), e);
			}
		}
	}
}
